#!/usr/bin/env python3

import os
import shlex

import common
from shell_helpers import LF

class Main(common.BuildCliFunction):
    def __init__(self):
        super().__init__(
            description='''\
Build our compiled userland examples.
'''
        )
        self.add_argument(
            '--has-package',
            action='append',
            default=[],
            help='''\
Indicate that a given package is present in the root filesystem, which
allows us to build examples that rely on it.
''',
        )
        self.add_argument(
            '--host',
            default=False,
            help='''\
Build the userland programs for the host instead of guest.
Use the host packaged cross toolchain.
''',
        )
        self.add_argument(
            '--make-args',
            default='',
        )
        self.add_argument(
            '--static',
            default=False,
            help='''\
Build the executables statically. TODO not implemented: Set the build id to 'static'
if one was not given explicitly.
''',
        )
        self.add_argument(
            'targets',
            default=[],
            help='''\
Build only the given userland programs.
Default: build all examples that have their package dependencies met.
For example, an OpenBLAS example can only be built if the target root filesystem
has the OpenBLAS libraries and headers installed.
''',
            nargs='*',
        )

    def build(self):
        build_dir = self.get_build_dir()
        os.makedirs(build_dir, exist_ok=True)
        if self.env['host']:
            allowed_toolchains = ['host']
        else:
            allowed_toolchains = ['buildroot']
        cc = self.get_toolchain_tool('gcc', allowed_toolchains=allowed_toolchains)
        cxx = self.get_toolchain_tool('g++', allowed_toolchains=allowed_toolchains)
        make_args = shlex.split(self.env['make_args'])
        if self.env['static']:
            make_args.extend(['CCFLAGS_EXTRA=-static', LF])
        self.sh.run_cmd(
            (
                [
                    'make', LF,
                    '-j', str(self.env['nproc']), LF,
                    'ARCH={}'.format(self.env['arch']), LF,
                    'CCFLAGS_SCRIPT={} {}'.format('-I', self.env['userland_source_dir']), LF,
                    'COMMON_DIR={}'.format(self.env['root_dir']), LF,
                    'CC={}'.format(cc), LF,
                    'CXX={}'.format(cxx), LF,
                    'PKG_CONFIG={}'.format(self.env['buildroot_pkg_config']), LF,
                    'STAGING_DIR={}'.format(self.env['buildroot_staging_dir']), LF,
                    'OUT_DIR={}'.format(build_dir), LF,
                ] +
                self.sh.add_newlines(['HAS_{}=y'.format(package.upper()) for package in self.env['has_package']]) +
                make_args +
                self.sh.add_newlines([os.path.join(build_dir, os.path.splitext(os.path.split(target)[1])[0]) + self.env['userland_build_ext'] for target in self.env['targets']])
            ),
            cwd=self.env['userland_source_dir'],
            extra_paths=[self.env['ccache_dir']],
        )
        self.sh.copy_dir_if_update_non_recursive(
            srcdir=build_dir,
            destdir=self.env['out_rootfs_overlay_dir'],
            filter_ext=self.env['userland_build_ext'],
        )

    def get_build_dir(self):
        return self.env['userland_build_dir']

if __name__ == '__main__':
    Main().cli()
